using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;
using System.Web.Security;
using IndyMosaic.Core.Email;

namespace IndyMosaic.Site.Controllers
{
    [Authorize (Roles = "Administrator")]
    public class AdministrationController : Controller
    {
        //
        // GET: /Administration/
        public ActionResult Index()
        {
            return View();
        }
    
        public ActionResult Users(bool? activeUsersOnly)
        {
            var users = Membership.GetAllUsers();
            
            return View(users);
        }

        public ActionResult ResetUserPassword(Guid id)
        {
            MembershipUser user = Membership.GetUser(id);
            string newPassword = user.ResetPassword();
            Membership.UpdateUser(user);
            string body = string.Format("Your password has been reset to: {0}/r/nDon't forget to change your password after you login.", newPassword);
            EmailUtility.SendEmail(EmailUtility.GetMailAddress(Membership.GetUser(), HttpContext.Profile["FullName"].ToString()),
                EmailUtility.GetMailAddress(user, null), "You password has been reset", body);
            return View();
        }

        public ActionResult EditUser(Guid id)
        {

            UserInformation ui = new UserInformation { User = Membership.GetUser(id), Roles = Roles.GetRolesForUser(Membership.GetUser(id).UserName) };
            return View(ui);
        
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult EditUser(Guid id, FormCollection collection)
        {
            MembershipUser user = Membership.GetUser(id);
            user.Email = collection["Email"];
            user.IsApproved = collection["IsActive"].StartsWith("true");

            if (Roles.GetRolesForUser(user.UserName).Count() > 0)
            {
                Roles.RemoveUserFromRoles(user.UserName, Roles.GetRolesForUser(user.UserName));
            }
            foreach (string roleName in Roles.GetAllRoles())
            {
                if (collection[roleName] != null)
                {
                    if (collection[roleName].StartsWith("true"))
                    {
                        Roles.AddUserToRole(user.UserName, roleName);
                    }
                }
            }

            Membership.UpdateUser(user);
            return Redirect("/Administration/Users");
        }

        
    }
    public class UserInformation
    {
        public MembershipUser User { get; set; }
        public string[] Roles { get; set; }

    }
}
